//
//  ThirdViewController.m
//  重新使用NSTimer
//
//  Created by xiakexing on 2018/5/14.
//  Copyright © 2018年 xiakexing. All rights reserved.
//

#import "ThirdViewController.h"
#import "NSTimer+ResolveCirRef.h"

//定义了一个__weak的self_weak_变量
#define weakifySelf  \
__weak __typeof(&*self)weakSelf = self;

//局域定义了一个__strong的self指针指向self_weak
#define strongifySelf \
__strong __typeof(&*weakSelf)self = weakSelf;

@interface ThirdViewController ()
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong) NSString * showStr;
@end

@implementation ThirdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor redColor];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn];
    btn.frame = CGRectMake(100, 100, 100, 100);
    [btn setTitle:@"点击" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor yellowColor];
    [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    
}
- (void)clickBtn:(UIButton *)btn{
    btn.selected = !btn.selected;
    NSString * str = @"";
    if (btn.selected == YES) {
        str = @"1";
    }else{
        str = @"2";
    }
    
    self.showStr = str;
    if (self.timer == nil) {
        weakifySelf
//        self.timer = [NSTimer resolve_scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *timer) {
//            strongifySelf
//            [self doThings];
//            NSLog(@"str:%@", self.showStr);
//        }];
        
        if (@available(iOS 10.0, *)) {
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
                strongifySelf
                NSLog(@"str:%@", self.showStr);
            }];
        } else {
            // Fallback on earlier versions
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
                
            }];
        }
    }
    
}
- (void)doThings{
//    NSLog(@"做一些事情...");
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    // 务必在当前线程调用invalidate方法，使得Runloop释放对timer的强引用(具体请参阅官方文档)
    NSLog(@"当前控制器被释放掉了...");
    [self.timer invalidate];
}

@end
